package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.IAccountService;


import com.stylefeng.guns.modular.huamao.service.ISktAgentsStockholderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.dao.AccountMapper;
import com.stylefeng.guns.modular.huamao.dao.AccountShopMapper;
import com.stylefeng.guns.modular.huamao.dao.SktAgentsMapper;
import com.stylefeng.guns.modular.huamao.dao.SktAgentsStockholderMapper;
import com.stylefeng.guns.modular.huamao.dao.SktShopApplysMapper;
import com.stylefeng.guns.modular.huamao.dao.SktShopApproveMapper;
import com.stylefeng.guns.modular.huamao.dao.SktShopsMapper;
import com.stylefeng.guns.modular.huamao.dao.SktStaffsMapper;
import com.stylefeng.guns.modular.huamao.dao.SktSysConfigsMapper;
import com.stylefeng.guns.modular.huamao.dao.UsersMapper;
import com.stylefeng.guns.modular.huamao.service.ISktStaffsService;

/**
 * <p>
 * 商城职员表 服务实现类
 * </p >
 *
 * @author ck123
 * @since 2018-04-25
 */
@Service
public class SktStaffsServiceImpl extends ServiceImpl<SktStaffsMapper, SktStaffs> implements ISktStaffsService {
	@Autowired
	private SktStaffsMapper sktStaffsMapper;
	@Autowired
	private SktShopApproveMapper sktShopApproveMapper;
	@Autowired
	private SktShopApplysMapper sktShopApplysMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private SktSysConfigsMapper sysConfigsMapper;
	@Autowired
	private AccountShopMapper accountShopMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private SktShopsMapper sktShopsMapper;
	@Autowired
	private SktAgentsMapper sktAgentsMapper;
	@Autowired
	private SktAgentsStockholderMapper sktAgentsStockholderMapper;
	@Autowired
	private ISktAgentsStockholderService sktAgentsStockholderService;
	@Autowired
	private IAccountService  accountService;
	@Override
	public List<SktShopIndustryDTO> sktStaffsfindAll(Page<SktShopIndustryDTO> page, SktShopIndustryDTO sktShopIndustryDTO) {
		Integer total = sktStaffsMapper.sktStaffsfindAllCount(sktShopIndustryDTO);
		page.setTotal(total);
		return sktStaffsMapper.sktStaffsfindAll(page,sktShopIndustryDTO);
	}
	@Override
	public List<SktShopIndustryDTO> sktStaffsfindup(SktShopIndustryDTO sktShopIndustryDTO) {
		return sktStaffsMapper.sktStaffsfindup(sktShopIndustryDTO);
	}
	@Override
	public void sktStaffsupdate(SktShopIndustryDTO sktShopIndustryDTO) {
		sktStaffsMapper.sktStaffsupdate(sktShopIndustryDTO);	
	}
	
	@Transactional
	@Override
	public String sktStaffsup1(SktShopIndustryDTO sktShopIndustryDTO ,Integer shiroUserId ) {

		String result = "";
		//判断是通过还是拒绝
		if(sktShopIndustryDTO.getShopStatus()==3){

			SktShopApprove shopApprove = sktShopApproveMapper.selectById(sktShopIndustryDTO.getApplyId());
			shopApprove.setCheckStaffId(shiroUserId);
			//判断该用户是否有商铺
			Integer userId = shopApprove.getUserId();
//			Integer shopCount = sktStaffsMapper.selectShops(userId);
//			if(ToolUtil.isNotEmpty(shopCount)&& shopCount != 0){//不为空
//				return "0";
//			}

			//更新用户状态
			Users users = new Users();
			users.setUserId(userId);
			users.setIsStore(1);
			usersMapper.updateById(users);
			
			//查询有没有shop表跟 shop账户表 说明申请了线上商家
			String isOk = shopAndShopAccount(userId);
			if ("SUCCESS".equals(isOk)){
				//查询店铺id 更新shop表状态
				SktShops sktShops = sktShopsMapper.selectShopsInfo(userId);
				sktShops.setStoreStatus(1);
				//更新shop
				sktShopsMapper.updateById(sktShops);
				//更新企业表状态
				sktStaffsMapper.sktStaffsup1(sktShopIndustryDTO);
			}else{// 没有新增shop表 跟 shop账户表
				//新增shops表
				SktShops sktShops = new SktShops();
				//BeanUtils.copyProperties(sktShops,sktShopIndustryDTO);

				sktShops.setUserId(userId);
				sktShops.setProvinceId(shopApprove.getProvinceId());
				sktShops.setCityId(shopApprove.getCityId());
				sktShops.setAreaId(shopApprove.getAreaId());
				sktShops.setIsLegal(shopApprove.getIsLegal());
				sktShops.setAuthorizationImg(shopApprove.getAuthorizationImg());
				sktShops.setLegalPerson(shopApprove.getLegalPerson());
				sktShops.setIDnumber(shopApprove.getIDnumber());
				sktShops.setLegalPersonImg(shopApprove.getLegalPersonImg());
				sktShops.setCompanyName(shopApprove.getCompanyName());
				sktShops.setStoreStatus(1);
				sktShops.setShopStatus(0);
				sktShops.setLicenseNo(shopApprove.getLicenseNo());
				sktShops.setCompanyType(shopApprove.getCompanyType());
				sktShops.setLicenseMerge(shopApprove.getLicenseMerge());
				sktShops.setLicenseImg(shopApprove.getLicenseImg());
				sktShops.setCodeImg(shopApprove.getCodeImg());
				sktShops.setTaxImg(shopApprove.getTaxImg());
				sktShops.setIndustry(shopApprove.getIndustry());
				sktShops.setShopName(shopApprove.getShopName());
				sktShops.setLogo(shopApprove.getLogo());
				sktShops.setTelephone(shopApprove.getTelephone());
				sktShops.setAddress(shopApprove.getAddress());
				sktShops.setCreateTime(new Date());
				sktShops.setBusinessQuota(new BigDecimal(0));
				Integer shops = sktShopsMapper.insert(sktShops);

				//新增店铺账户表 skt_account_shop
				AccountShop accountShop = new AccountShop();
				accountShop.setUserId(userId);
				accountShop.setShopId(sktShops.getShopId());
				accountShop.setCreateTime(new Date());
				accountShopMapper.insert(accountShop);
				//修改个人账户shopId
				sktStaffsMapper.updataAccount(sktShops.getShopId(),userId);
			}


			//更新代理商家数
			SktAgents sktAgents = sktStaffsMapper.selectAgents(shopApprove);

			if(ToolUtil.isEmpty(sktAgents)){
				return "2";
			}
			Integer agentId = sktAgents.getAgentId();
			if(sktAgents.getAlevel() == 10){
				//更新本级代理商家数量
				sktAgents.setStoreNum(sktAgents.getStoreNum()+1);
				sktAgentsMapper.updateById(sktAgents);
				//检查开启代理公司运营账号货分红账号
				String orderNo = "shangqirenzheng"+sktShopIndustryDTO.getApplyId();
				Map<String, Object> map1 =sktAgentsStockholderService.checkRunOrProfit(agentId, orderNo);
				if ("00".equals(map1.get("code").toString())){
					return map1.get("msg").toString();
				}
			}
			if(sktAgents.getAlevel() == 11){
				//更新本级代理商家数量
				sktAgents.setStoreNum(sktAgents.getStoreNum()+1);
				sktAgentsMapper.updateById(sktAgents);
				//更新上一级商家数量
				sktAgents.setCityId(0);
				sktStaffsMapper.updataAgentNum(sktAgents);
				//检查开启代理公司运营账号货分红账号
				String orderNo = "shangqirenzheng"+sktShopIndustryDTO.getApplyId();
				Map<String, Object> map1 =sktAgentsStockholderService.checkRunOrProfit(agentId, orderNo);
				if ("00".equals(map1.get("code").toString())){
					return map1.get("msg").toString();
				}
			}
			if(sktAgents.getAlevel() == 12){
				//更新本级代理商家数量
				sktAgents.setStoreNum(sktAgents.getStoreNum()+1);
				sktAgentsMapper.updateById(sktAgents);
				//更新上一级商家数量
				sktAgents.setAreaId(0);
				sktStaffsMapper.updataAgentNum(sktAgents);
				//更新上一级商家数量
				sktAgents.setCityId(0);
				sktStaffsMapper.updataAgentNum(sktAgents);
				//检查开启代理公司运营账号货分红账号
				String orderNo = "shangqirenzheng"+sktShopIndustryDTO.getApplyId();
				Map<String, Object> map1 =sktAgentsStockholderService.checkRunOrProfit(agentId, orderNo);
				if ("00".equals(map1.get("code").toString())){
					return map1.get("msg").toString();
				}
			}
			//看推荐人是不是代理  如果是更新代理股东表 
			Integer shId = sktStaffsMapper.selectIsAgentsStockholder(userId);
			if(ToolUtil.isNotEmpty(shId)){
				sktStaffsMapper.updateAgentsStockholder(shId);
				//查是否符号完成目标
				SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
				String fieldValue = sysConfig.getFieldValue();
				Integer holderDividendNum=Integer.parseInt(fieldValue);
				//查找skt_agents_stockholder --storeFreezeDividend
				Account account = accountMapper.selectAccountByuserId(sktShopIndustryDTO.getUserId());
				SktAgentsStockholder sktAgentsStockholder = sktAgentsStockholderMapper.selectById(shId);
				if( holderDividendNum<=sktAgentsStockholder.getStoreNum() ){
					if(sktAgentsStockholder.getStoreFreezeDividend().compareTo(BigDecimal.ZERO)==1){
						// 清空storeFreezeDividend
						sktAgentsStockholder.setStoreFreezeDividend(BigDecimal.ZERO);
						//生成积分流水
						accountService.insertLogScoreFreeze(userId,31,"4",sktAgentsStockholder.getStoreFreezeDividend(),"转入到正式积分账户",sktAgentsStockholder.getStoreFreezeDividend(),-1,userId);
						accountService.insertLogScore(userId,11,"4",account.getScore(),"分红获得",sktAgentsStockholder.getStoreFreezeDividend(),1,userId);
						//如果有值  修改用户账户表
						account.setScore(account.getScore().add(sktAgentsStockholder.getStoreFreezeDividend()));
						account.setTotalScore(account.getTotalScore().add(sktAgentsStockholder.getStoreFreezeDividend()));
						accountService.updateById(account);
					}
				}
//				accountService.fenRun(sktAgents.getAgentId(),shId );

			}
			result = "1";
		}else{
			//更新表状态 审核时间
			SktShopApprove sktShopApprove = new SktShopApprove();
			sktShopApprove.setApplyId(sktShopIndustryDTO.getApplyId());
			sktShopApprove.setShopStatus(sktShopIndustryDTO.getShopStatus());
			sktShopApprove.setStatusDesc(sktShopIndustryDTO.getStatusDesc());
			sktShopApprove.setCheckTime(new Date());
			sktShopApprove.setCheckStaffId(shiroUserId);
			sktShopApproveMapper.updateById(sktShopApprove);
			result = "1";
		}
		return result;
	}

	/**
	 * 根据用户id查询用户shop表跟shop账户表
	 * @param usersId
	 * @return
	 */
	public String shopAndShopAccount(Integer usersId){
		Integer shopCount = sktStaffsMapper.selectShopsCount(usersId);
		Integer shopAcountCount = sktStaffsMapper.selectShopsAcountCount(usersId);
		if (shopCount.intValue() != 0 && shopAcountCount.intValue() != 0){
			return "SUCCESS";
		}
		return  "EMPTY";
	}

}